package com.qushiyun.devops.admin.sync.job;

import java.util.LinkedHashMap;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.anyline.data.jdbc.ds.DataSourceHolder;
import org.anyline.metadata.Function;
import org.anyline.service.AnylineService;
import org.springframework.stereotype.Component;

/**
 * 函数辅助
 *
 * @author zhouzx
 */
@Component
@AllArgsConstructor
@Slf4j
public class FunctionHelper {

    public static final String DROP_FUNCTION_DDL = "drop function if exists %s";

    private final AnylineService anylineService;

    public void sync(String from, String to) {
        log.info("begin sync function : {}->{}", from, to);
        DataSourceHolder.setDataSource(from);
        LinkedHashMap<String, Function> functions = anylineService.metadata().functions();
        for (Function function : functions.values()) {
            DataSourceHolder.setDataSource(from);
            List<String> ddls = anylineService.metadata().ddl(function);
            DataSourceHolder.setDataSource(to);
            anylineService.execute(String.format(DROP_FUNCTION_DDL, function.getName()));
            String ddl = ddls.get(0).replaceAll("DEFINER=.*@`%` ", " ");
            anylineService.execute(ddl);
        }
        log.info("sync function : {}->{} success!", from, to);
    }
}
